<?php
/**
 * ===============================================
 * 版权所有 2019-2050 青岛铁锤科技有限公司，并保留所有权利。
 * 网站地址: http://www.huaxianling.com
 * ===============================================
 * Author: Rag Hu
 * Created Time: 2019/6/25 10:20
 * Modified Time: 2019/6/25 10:20
 * Version: 2.0
 */

namespace App\Modules\Store\Repositories;

use App\Exceptions\NotFoundException;
use App\Models\Store;
use App\Lib\Utilities;
use App\Modules\Order\Repositories\RoyaltyRepository;
use App\Modules\Store\Validators\StoreValidator;
use Flower\Core\Repository\Exceptions\ValidatorException;
use Illuminate\Support\Facades\DB;
use Flower\Core\Repository\Eloquent\BaseRepository;
use Illuminate\Support\MessageBag;
use tests\Mockery\Adapter\Phpunit\EmptyTestCase;

class StoreRepository extends BaseRepository
{
    public function model()
    {
        return Store::class;
    }


    /**
     * Specify Validator class name
     * @return mixed
     */
    public function validator()
    {
        return StoreValidator::class;
    }

    /*
     * 新增店铺
     */
    public function createStore($user_id,
                                $name,
                                $phone,
                                $wechat,
                                $profile,
                                $longitude,
                                $latitude,
                                $invite_code,
                                $adcode,
                                $uid,
                                $address)
    {
        $new_store_data = [
            'user_id' => $user_id,
            'name' => $name,
            'phone' => $phone,
            'wechat' => $wechat,
            'profile' => $profile,
            'longitude' => $longitude,
            'latitude' => $latitude,
            'invite_code' => $invite_code,
            'adcode' => $adcode,
            'uid' => $uid,
            'address' => $address,
        ];
        return $this->create($new_store_data);

    }

    /*
     * 修改店铺信息
     */
    public function updateStore($store_id, $updateData)
    {
        unset($updateData['store_id']);
        return $this->update($updateData, $store_id);
    }



    /**
     * 获取店铺营业时间
     * @param $storeId
     * @param $date
     * @return array
     */
    public function getOpenTimes($storeId, $date)
    {
        $map = [
            'id' => $storeId,
            'status' => 1,
        ];
        $data = $this->model->where($map)->first(['id', 'open_time', 'close_time']);
        return $this->transHalfHour($date, $data['open_time'], $data['close_time']);
    }

    /**
     * 把店铺的营业时间换算成每隔半小时的数据
     */
    protected function transHalfHour($date, $startTime, $endTime)
    {
        $startTime = strtotime($date . " " . $startTime . ":01");
        $endTime = strtotime($date . " " . $endTime . ":01");
        $list = [];
        do {
            $list[] = $startTime;
            $startTime += 1800;
        } while ($startTime < $endTime);
        return $list;
    }


    public function isExited($storeId)
    {
        $store = $this->find($storeId);
        if (empty($store)) {
            throw new NotFoundException(['msg' => '该店铺信息不存在']);
        }
        return $store;
    }


    public function findStoreRankByStoreId($storeId)
    {
        return $this->model->with('picture:id,image')->with(['storeRank' => function ($v) {
            $v->whereDate('created_at', date('Y-m-d', time()));
        }])->find($storeId);
    }

    /**
     * 地区列表
     * @return array
     */
    public function storeIdsByCode()
    {
        // 获取所有店铺的位置信息
        $storeLocation = $this->withCount('userStore')->findWhere(['status' => config('constant.yes')])->toArray();
        if (!empty($storeLocation)) {
            $storeLocation = array_map(function ($v) {
                return [
                    'id' => $v['id'],
                    'adcode' => $v['adcode'],
                    'user_count' => $v['user_store_count'],
                    'expenditure' => $v['expenditure']
                ];
            }, $storeLocation);
        }
        return $storeLocation;
    }


    /**
     * 门店排名 计算并插入数据库操作
     * @return mixed
     */
    public function rankStore()
    {
        // 获取所有店铺的位置信息
        $storeLocation = $this->model->where(['status' => config('constant.yes')])->get(['id', 'adcode', 'status'])->toArray();
        // 用adcode给数组分组
        $storeInfo = Utilities::arrayColumnGroup($storeLocation, null, 'adcode');
        // 计算某个店铺的人均工资
        // $date = '2019-07-08';
        $date = date('Y-m-d', time());
        // 计算本地区的所有店铺的人均工资
        $list = array_map(function ($v) use ($date) {
            $v = array_map(function ($v2) use ($date) {
                return $v2 = [
                    // 查询店铺的人员工资平均值
                    'value' => (new RoyaltyRepository())->userSalary($v2['id'], [], $date, true),
                    'store_id' => $v2['id'],
                    'adcode' => $v2['adcode'],
                    'rank_date' => strtotime($date) - 86400,
                ];
            }, $v);
            //排序操作
            $value = array_column($v, 'value');
            array_multisort($value, SORT_DESC, $v);
            return $v;
        }, $storeInfo);
        if (empty($list)) {
            $msg = '店铺排名的计算结果信息为空';
            Log::info($msg . '时间' . date('Y-m-d H:i:s', time()));
            throw new ValidatorException(new MessageBag([$msg]));
        }
        $result = array_map(function ($v) {
            // 插入数据操作
            return $res = (new StoreRankRepository())->add(
            // 格式化插入数据
                array_map(function ($v2, $v3) {
                    return [
                        'value' => $v2['value'],
                        'store_id' => $v2['store_id'],
                        'adcode' => $v2['adcode'],
                        'rank_date' => $v2['rank_date'],
                        'level' => $v3 + 1,
                    ];
                }, $v, array_keys($v)));
        }, $list);
        // 处理返回操作的bool值
        return array_reduce($result, function ($v, $v2) {
            return $v = $v && $v2;
        }, true);
    }


    /**
     * 获取理发店所有理发师Ids
     * @param $storeId
     * @return array|int
     */
//    public function getBarbersIds($storeId)
//    {
//        try {
//            $users = $this->find($storeId)->user()->where(['rid' => config('constant.role.barber')])->get()->toArray();
//            $userIds = empty($users) ? [] : array_column($users, 'id');
//            return $userIds;
//        } catch (\BadMethodCallException $e) {
//            return [];
//        }
//    }

    /**
     * 获取店铺列表
     * @param $requestData
     * @return mixed
     */
    public function getStoreList($requestData)
    {
        $pageSize = isset($requestData['pageSize']) ? $requestData['pageSize'] : 10;
        $res = $this->model->where(['status' => 1])->paginate($pageSize, ['*'], 'paginate');
        return Utilities::dealPage($res);
    }

    public function getStoreNameById($store_id)
    {
        return $this->model->select(
            [
                'id as store_id',
                'name as store_name',
                'profile',
                'logo'
            ])
            ->with(['logo'=>function($query){
                $query->select(['id','image']);
            }])
            ->where(['id' => $store_id])
            ->first();
    }

    /**
     * 获取店铺信息
     * @param $storeList
     * @return mixed
     */
    public function getStoreInfoList($storeList)
    {
        return $this->with('picture')->findWhereIn('id', $storeList);
    }

    /**
     * 判断同地区有无重名店铺
     * @param $name
     * @param $adcode
     * @return mixed
     */
    public function checkCityDoubleNameStore($name, $adcode)
    {
        return $this->findByField(['name' => $name, 'adcode' => $adcode])->first();
    }

    /**
     * 店铺是否开门
     * @param $storeId
     * @return mixed
     * @throws NotFoundException
     */
    public function isOpen($storeId)
    {
        $info = $this->isExited($storeId);
        return $info->status;
    }

    /**
     * 获取店铺信息
     * @param $storeId
     * @return mixed
     */
    public function getStoreInfoById($storeId)
    {
        return $this->with('picture')->find($storeId);
    }

    /**
     * 计算店铺员工的基本工资
     * @return mixed
     */
    public function getUserBaseSalary()
    {
        $baseSalaryList = $this->withCount(['userStore as salary_sum' => function ($query) {
            $query->select(DB::raw("sum(salary) as salarysum"));
        }]
        )->get()->toArray();
        return empty($baseSalaryList) ? [] : array_column($baseSalaryList, null, 'id');
    }


    /**
     * 保存门店LOGO
     * @param $store_id
     * @param $logo
     */
    public function updateLogo($store_id, $logo)
    {
        $this->update(['logo' => $logo], $store_id);
    }

    /**
     * 获取创始人id
     * @param $store_id
     * @return mixed
     */
    public function getFounderId($store_id)
    {
        return $this->find($store_id)->user_id;
    }


	/**
	 * 获取所有的营业的店铺id
	 * @return mixed
	 */
    public function getStoreAllIds(){
    	return $this->model
		    ->where(['status'=>config('constant.yes')])
		    ->pluck('id')
		    ->toArray();
    }


	/**
	 * 计算店铺的固定支出
	 * @param $dateType
	 * @param $storeId
	 * @return float
	 */
    public function getExpenditure($dateType,$storeId){
    	$data = $this->model->selectRaw('(water_expenditure+room_expenditure+internal_expenditure) as expenditure')->where(['id'=>$storeId])->first();
		return  $dateType ? $data->expenditure : round($data->expenditure/ date('t') ,2);
    }
}